// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  const { OPENID, APPID, UNIONID } = cloud.getWXContext()

  const usersCollection = cloud.database().collection('users')
  let user = (await usersCollection.where({openid: OPENID}).get()).data[0]
  if (!user) {
    user = {
      openid: OPENID,
      nickName: '用户' + OPENID.substr(0, 8)
    }
    const res = await usersCollection.add({
      data: user
    })
    user.id = res._id
  }

  return {
    userInfo: {
      ...user,
    },
  }
}